package com.lei.controller;

import com.lei.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author Lei Chu
 * @Date 2020/10/15 19:01
 */
public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求路径
        String url = req.getRequestURI();
        //获取请求路径的最后“/”后面的字段，用于调用servlet中的方法
        String methodStr = url.substring(url.lastIndexOf("/") + 1);

        if ("".equals(methodStr) || methodStr == null) {
            methodStr = Constants.INDEX;
        }
        //获得当前类的 Class 实例
        Class cla = this.getClass();

        try {
            //根据方法名获得Method对象
            Method method = cla.getMethod(methodStr, HttpServletRequest.class, HttpServletResponse.class);
            //执行方法
            Object result = method.invoke(this, req, resp);
            //处理返回的result  重定向/请求转发
            if (result != null) {
                String str =result+"";
                //重定向
                if (str.startsWith(Constants.REDIRECT)) {
                    // 获取重定向路径
                    String path = str.substring(str.indexOf(":") + 1);
                    resp.sendRedirect(path);
                } else if (str.startsWith(Constants.FORWARD)) {
                    //获取请求转发路径
                    String path = str.substring(str.indexOf(":") + 1);
                    req.getRequestDispatcher(path).forward(req, resp);
                } else {
                    //处理的是异步请求，只需要向前段写会数据即可
                    PrintWriter out = resp.getWriter();
                    out.write(str);
                    out.close();
                }
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    /**
     * 功能描述: 当访问的url 没有具体的方法路径的时候，我们会转到登录页面
     *
     * @param req  Re
     * @param resp Res
     * @return java.lang.String
     */
    public String index(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        return Constants.FORWARD + "/index.jsp";
    }

    /**
     * 功能描述:检测一个字符串能否转化成int
     * @param string String
     * @return java.lang.Boolean
     */
    public Boolean isInt(String string){
        try {
            Integer.parseInt(string);
        } catch (NumberFormatException e) {
           return false;
        }
        return true;
    }

}
